package com.ithe.gateway;

/**
 * Created by zxd on 2022/8/21
 */

import com.ithe.gateway.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Created by zxd on 2022/4/8 14:36
 */
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();

        String path = request.getPath().value();

        //判断是访问移动端接口还是管理端接口
        if(path.contains("/app-api")){
            log.info("访问移动端接口:{}",path);
            return chain.filter(exchange);

        }else{

            log.info("访问管理端接口:{}",path);
            if(path.contains("/admin/login")){
                log.info("登录操作直接放行...");
                return chain.filter(exchange);
            }

            String token = request.getHeaders().getFirst("token");
            if(StringUtils.isEmpty(token)){
                token=request.getQueryParams().getFirst("token");
                if(StringUtils.isEmpty(token)){
                    log.error("token不能为空!");
                    ServerHttpResponse response = exchange.getResponse();
                    return ResponseUtils.writeErrorInfo(response, ResultCode.TOKEN_INVALID_OR_EXPIRED);
                }
            }

            //TODO 认证和权限鉴定

            //向下游进行转发
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}